import { login, register, updateUserInfo } from "@/service/loginRegister"
import {
  ILoginInfo,
  IRegister,
  IUpdateUserInfo
} from "@/service/loginRegister/types"
import { IUserInfo } from "./types"
import router from "@/router"
import CacheLocal from "@/utils/cacheLocal"
import { ActionTree } from "vuex"
import { IUserState } from "./types"
import { IState } from "@/store/types"
const actions: ActionTree<IUserState, IState> = {
  async userLogin({ commit }, payload: ILoginInfo) {
    console.log("登录")

    const res = await login(payload)
    const token = res.data.token
    if (token) {
      CacheLocal.setItem("LSToken", token)
    }
    if (res.success) {
      commit("saveUserInfo", res.data)
      return res.msg
    } else {
      return false
    }
  },

  //注册
  async userRegister({ commit }, payload: IRegister) {
    const res = await register(payload)
  },

  async updateUser({ commit, state }, payload: IUpdateUserInfo) {
    console.log("rootState ", state.updateUserInfo)

    const res = await updateUserInfo(state.updateUserInfo)
    if (res) {
      console.log("res", res)
      router.push("/login")
    }
  },

  //自动保存用户信息
  autoSaveUserInfo({ commit }) {
    const userInfo: IUserInfo = CacheLocal.getItem("LSUserInfo")
    // const router = useRouter()
    if (userInfo) {
      commit("saveUserInfo", userInfo)
    } else {
      console.log("没有，返回登陆", router)
      router.push("/login")
    }
  }
}

export type IUserActions = {
  moduleUser: {
    // acGetFriendLists: () => void;
    userLogin: () => any
    userRegister: () => any
    updateUser: () => any
    autoSaveUserInfo: () => any
  }
}

export { actions }
